/*******************************************************************************
 * Licensed Materials - Property of IBM
 * (c) Copyright IBM Corporation 2007. All Rights Reserved.
 * 
 * Note to U.S. Government Users Restricted Rights:
 * Use, duplication or disclosure restricted by GSA ADP Schedule
 * Contract with IBM Corp. 
 *******************************************************************************/
package com.example.jazztalk.rcp.ui.actions;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.example.jazztalk.client.IJazzTalkClientLibrary;
import com.ibm.team.repository.client.ITeamRepository;
import com.ibm.team.repository.common.TeamRepositoryException;

public abstract class AbstractJazzTalkAction implements IObjectActionDelegate {

	private Shell _shell;
	private ITeamRepository _repository;

	protected Shell getShell() {
		return _shell;
	}

	protected ITeamRepository getRepository() {
		return _repository;
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		_shell = targetPart.getSite().getShell();
	}

	public void selectionChanged(IAction action, ISelection selection) {
		_repository = null;

		if (selection instanceof IStructuredSelection) {
			Object first = ((IStructuredSelection) selection).getFirstElement();
			if (first instanceof ITeamRepository) {
				_repository = (ITeamRepository) first;
			}
		}
	}

	public void run(IAction action) {
		queryUser();
		//showFiltersDialog();
		Job job = new Job("JazzMail") {
			protected IStatus run(IProgressMonitor monitor) {
				try {
					callService(monitor);

					getShell().getDisplay().asyncExec(new Runnable() {
						public void run() {
							showResults();
						}
					});

				} catch (TeamRepositoryException e) {
					e.printStackTrace();
				}
				return Status.OK_STATUS;
			}
		};
		job.schedule();
	}

	protected void queryUser() {
	}
	protected void showFiltersDialog() {
		
	}
	protected abstract void callService(IProgressMonitor monitor)
			throws TeamRepositoryException;

	protected void showResults() {

	}

	protected IJazzTalkClientLibrary getClientLibrary() {
		ITeamRepository repository = getRepository();
		return (IJazzTalkClientLibrary) repository
				.getClientLibrary(IJazzTalkClientLibrary.class);
	}
}
